package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.search.common.PageResult;
import com.hmall.search.pojo.Item;
import com.hmall.search.pojo.ItemPageQueryDTO;
import com.hmall.search.pojo.ItemVO;
import com.hmall.search.service.IsearchService;
import com.tdunning.math.stats.Sort;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class IsearchServiceImpl implements IsearchService {

    public static final String ITEM = "item";
    private final RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult<ItemVO> listPage(ItemPageQueryDTO itemPageQueryDTO) {
        int from = (itemPageQueryDTO.getPage() - 1) * itemPageQueryDTO.getSize();
        SearchRequest searchRequest = new SearchRequest(ITEM);
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(itemPageQueryDTO);

        searchRequest.source().query(boolQueryBuilder);
        //分页
        searchRequest.source()
                .from(from)
                .size(itemPageQueryDTO.getSize());
        //todo 排序
        String sortBy = itemPageQueryDTO.getSortBy();
        if ("sold".equals(sortBy)) {
            searchRequest.source().sort(sortBy, SortOrder.DESC);
        } else if ("price".equals(sortBy)) {
            searchRequest.source().sort(sortBy, SortOrder.ASC);
        }
        //todo 高亮
        searchRequest.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        //todo 广告
        searchRequest.source()
                .query(
                QueryBuilders.functionScoreQuery(
                        boolQueryBuilder,
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        QueryBuilders.termQuery("isAD", true),
                                        ScoreFunctionBuilders.weightFactorFunction(10f)
                                )
                        }
                ).boostMode(CombineFunction.SUM)
        );
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value;
            SearchHit[] hitsHits = hits.getHits();
            List<ItemVO> itemVOS = Arrays.stream(hitsHits).map(hit -> {
                String sourceAsString = hit.getSourceAsString();
                ItemVO itemVO = JSON.parseObject(sourceAsString, ItemVO.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0){
                    HighlightField name = highlightFields.get("name");
                    String value = name.getFragments()[0].string();
                    itemVO.setName(value);
                }
                return itemVO;
            }).collect(Collectors.toList());
            PageResult<ItemVO> pageResult = new PageResult<>();
            pageResult.setTotal(total);
            pageResult.setList(itemVOS);
            return pageResult;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> suggestion(String key) {
        SearchRequest searchRequest = new SearchRequest(ITEM);
        String suggestionSuggest = "suggestionSuggest";
        searchRequest.source().suggest(
                new SuggestBuilder()
                        .addSuggestion(
                                suggestionSuggest,
                                SuggestBuilders.completionSuggestion("suggestion")
                                        .prefix(key)
                                        .skipDuplicates(true)
                                        .size(10)
                        )
        );
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion completionSuggestion = suggest.getSuggestion(suggestionSuggest);
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            List<String> collect = options.stream().map(option -> {
                String string = option.getText().string();
                return string;
            }).collect(Collectors.toList());
            return collect;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(ItemPageQueryDTO itemPageQueryDTO) {
        SearchRequest searchRequest = new SearchRequest(ITEM);
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(itemPageQueryDTO);
        String brandAgg = "brandAgg";
        String categoryAgg = "categoryAgg";
        String brand = "brand";
        String category = "category";
        searchRequest.source()
                .query(boolQueryBuilder)
                .size(0)
                .aggregation(
                        AggregationBuilders
                                .terms(brandAgg)
                                .field(brand)
                                .size(20)
                )
                .aggregation(
                        AggregationBuilders
                                .terms(categoryAgg)
                                .field(category)
                                .size(20)
                );
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();

            ParsedStringTerms aggregationCategory = aggregations.get(categoryAgg);
            List<? extends Terms.Bucket> categoryBuckets = aggregationCategory.getBuckets();
            List<String> categoryCollect = categoryBuckets.stream().map(bucket -> {
                String keyAsString = bucket.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());

            ParsedStringTerms aggregationBrand = aggregations.get(brandAgg);
            List<? extends Terms.Bucket> brandBuckets = aggregationBrand.getBuckets();
            List<String> brandCollect = brandBuckets.stream().map(bucket -> {
                String keyAsString = bucket.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());

            Map<String, List<String>> result = new HashMap<>();
            result.put(brand, brandCollect);
            result.put(category, categoryCollect);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static BoolQueryBuilder getBoolQueryBuilder(ItemPageQueryDTO itemPageQueryDTO) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 需求一的查询
        if (StringUtils.isBlank(itemPageQueryDTO.getKey())) {
            // 2.1 如果key为空则查询全部
            boolQuery
                    .must(
                            QueryBuilders
                                    .matchAllQuery()
                    );
        } else {
            // 2.2 如果key不为空则查询all字段
            boolQuery
                    .must(
                            QueryBuilders
                                    .matchQuery("all", itemPageQueryDTO.getKey())
                    );
        }
        // 需求二：支持通过分类、品牌、价格区间 进行过滤数据
        if (StringUtils.isNoneBlank(itemPageQueryDTO.getCategory())){
            //分类不为空，则增加分类条件
            boolQuery
                    .filter(
                            QueryBuilders
                                    .matchQuery("category",itemPageQueryDTO.getCategory())
                    );
        }
        if (StringUtils.isNoneBlank(itemPageQueryDTO.getBrand())) {
            // 品牌不为空，则增加品牌条件
            boolQuery
                    .filter(
                            QueryBuilders
                                    .matchQuery("brand", itemPageQueryDTO.getBrand())
                    );
        }
        if (Objects.nonNull(itemPageQueryDTO.getMinPrice()) &&
                Objects.nonNull(itemPageQueryDTO.getMaxPrice())) {
            // 价格不为空，则增加价格条件
            boolQuery
                    .filter(
                            QueryBuilders.rangeQuery("price")
                                    .lte(itemPageQueryDTO.getMaxPrice() * 100)//小于最大值
                                    .gte(itemPageQueryDTO.getMinPrice() * 100)//大于最小值
            );
        }
        return boolQuery;
    }
}












